import copy

from PySide6.QtCore import QDateTime, Slot, Qt
from PySide6.QtWidgets import QMessageBox, QDialog, QTableWidgetItem, QMainWindow, QButtonGroup, QSlider
from PySide6.QtGui import QIcon, QColor

from Devices.Chiot.BsDevs.ComDev.Forms.ComDevWindow import ComDevWindow
from Devices.Chiot.BsDevs.Dimmer.DimmerDevice import DimmerDevice
from Devices.Chiot.BsDevs.Dimmer.DimmerParser import DimmerParser
from Components.MessageBoxFunc import MessageBoxFunc
from Devices.Chiot.BsDevs.Dimmer.Forms.DimmerWindow_UI import Ui_FormDimmerWindow
from Devices.Chiot.BsDevs.Dimmer.Forms.TimerSetWindow import TimerSetWindow

class DimmerWindow(ComDevWindow):
    # 0、窗体初始化、状态变量初始化
    def __init__(self, supportDevice, parent = None):
        # 注意在实现特有设备时，一定要先将其ui对象加载完毕
        super().__init__(supportDevice, parent)
        self.FullStatus = DimmerDevice.DimmerFullStatus()

        self._ui = Ui_FormDimmerWindow()
        self._ui.setupUi(self)
        self.initUiWindow()
        self.SetupUi(self._ui)

        self._ui.horizontalSlider_brightness.setTracking(True)
        self._ui.horizontalSlider_pwmDuty.setTracking(False)
        self._ui.horizontalSlider_brightness.setTickPosition(QSlider.TicksBelow)
        self._ui.horizontalSlider_pwmDuty.setTickPosition(QSlider.TicksBelow)
        self._ui.horizontalSlider_brightness.valueChanged.connect(self.on_setBrightness)
        self._ui.horizontalSlider_pwmDuty.valueChanged.connect(self.on_setPwmDuty)
        self._ui.pushButton_setVoltageFreq.clicked.connect(self.on_setVoltageFreq)
        self.__TimerSetWindow = TimerSetWindow()
        # self.testUi()

    def on_setVoltageFreq(self):
        self._ui.comboBox_voltageFreq.blockSignals(True)
        
        freqStr = self._ui.comboBox_voltageFreq.currentText().strip()
        try:
            cmd = DimmerParser.PackSetVoltageParam("freq", int(freqStr))
            self.SendCommandText(cmd)
            if -1 == self._ui.comboBox_voltageFreq.findText(freqStr):
                self._ui.comboBox_voltageFreq.addItem(freqStr)
                self._ui.comboBox_voltageFreq.setCurrentIndex(self._ui.comboBox_voltageFreq.count() - 1)
        except Exception as e: 
            print("设置电压频率出现异常: %s"%e)
            self.ShowMessageBox("设置电压频率", "无效数据: "+freqStr, QMessageBox.Critical)

        self._ui.comboBox_voltageFreq.blockSignals(False)


    def on_setPwmDuty(self):
        self._ui.label_setPwmDuty.blockSignals(True)
        self._ui.horizontalSlider_pwmDuty.blockSignals(True)

        duty = self._ui.horizontalSlider_pwmDuty.value()
        self._ui.label_setPwmDuty.setText(str(duty))
        
        self._ui.label_setPwmDuty.blockSignals(False)
        self._ui.horizontalSlider_pwmDuty.blockSignals(False)

        if (duty != self.FullStatus.pwmDuty):
            cmd = DimmerParser.PackSetVoltageParam("duty", duty)
            self.SendCommandText(cmd)

    def on_setBrightness(self):
        self._ui.label_setBrightness.blockSignals(True)
        self._ui.horizontalSlider_brightness.blockSignals(True)

        brightness = self._ui.horizontalSlider_brightness.value()
        self._ui.label_setBrightness.setText(str(brightness))
        
        self._ui.label_setBrightness.blockSignals(False)
        self._ui.horizontalSlider_brightness.blockSignals(False)

        if (brightness != self.FullStatus.brightness):
            cmd = DimmerParser.PackSetAttr("brightness", "brightness", brightness)
            self.SendCommandText(cmd)

     # 1、数据解析
    def setHeartbeatStatus(self):
        #定时器
        self._ui.tableWidget_timers.clearContents()
        self._ui.tableWidget_timers.setRowCount(0)
        for timer in self.FullStatus.timers:
            if timer!= None:
                self.SetTimerToList(timer)

        #倒计时
        if 0 != self.FullStatus.delay.enable:
            self._ui.label_delayId.setText(self.FullStatus.delay.id)
            self._ui.dateTimeEdit_delayExecTime.setDateTime(QDateTime.fromSecsSinceEpoch(self.FullStatus.delay.end))
            self._ui.label_delayNotion.setVisible(False)

            switchOnoff = self.FullStatus.delay.services[0].paraValue
            self._ui.comboBox_delaySwitchCtrl.setCurrentIndex(switchOnoff)
            for srv in self.FullStatus.delay.services:
                if srv.serviceId == "switch":
                    pass
                else:
                    print(__func__, "Parse Timer, Unknown services:", srv.serviceId)
        else:
            self._ui.label_delayId.clear()
            self._ui.dateTimeEdit_delayExecTime.setDateTime(QDateTime.currentDateTime())
            self._ui.label_delayNotion.setVisible(True)

    def CmdRptStatusReceived(self, msgValue):
        if DimmerParser.ParseRptStatus(msgValue, self.FullStatus):
            self.setFullStatus()

    def CmdHeartbeatReceived(self, msgValue):
        if DimmerParser.ParseHeartbeat(msgValue, self.FullStatus):
            self.setFullStatus()
            self.setHeartbeatStatus()

    def CmdFullStatusReceived(self, msgValue):
        if DimmerParser.ParseHeartbeat(msgValue, self.FullStatus):
            self.setFullStatus()

    def CmdMsgValueReceived(self, msgName, msgValue):
        if msgName == "setVoltageParam":
            ret = int(msgValue["ret"])
            self.ShowMessageBox("设置调光参数", "%s!" % ("成功" if ret != 0 else "失败"), QMessageBox.Information if ret != 0 else QMessageBox.Critical)

    # 2、运行状态
    def setFullStatus(self):
        self._ui.label_switchStatus.setText("打开" if self.FullStatus.switchStatus else "关闭")
        self._ui.label_brightness.setText("{}%".format(self.FullStatus.brightness))
        
        self._ui.horizontalSlider_brightness.blockSignals(True)
        self._ui.horizontalSlider_pwmDuty.blockSignals(True)
        self._ui.comboBox_voltageFreq.blockSignals(True)
        self._ui.radioButton_switchCtrl.blockSignals(True)
        
        self._ui.horizontalSlider_brightness.setValue(self.FullStatus.brightness)
        self._ui.horizontalSlider_pwmDuty.setValue(self.FullStatus.pwmDuty)
        # if 60 == self.FullStatus.voltageFreq or 50 == self.FullStatus.voltageFreq:
        #     self._ui.comboBox_voltageFreq.setCurrentIndex(1 if 60 == self.FullStatus.voltageFreq else 1)
        # TODO 定版时固定
        freqIdx = self._ui.comboBox_voltageFreq.findText(str(self.FullStatus.voltageFreq))
        if -1 != freqIdx:
            self._ui.comboBox_voltageFreq.setCurrentIndex(freqIdx)
        else:
            self._ui.comboBox_voltageFreq.addItem(str(self.FullStatus.voltageFreq))
            self._ui.comboBox_voltageFreq.setCurrentIndex(self._ui.comboBox_voltageFreq.count() - 1)

        self._ui.radioButton_switchCtrl.setChecked(True if self.FullStatus.switchStatus else False)

        self._ui.horizontalSlider_brightness.blockSignals(False)
        self._ui.horizontalSlider_pwmDuty.blockSignals(False)
        self._ui.comboBox_voltageFreq.blockSignals(False)
        self._ui.radioButton_switchCtrl.blockSignals(False)
    
    # 3、设备控制
    @Slot(bool)
    def on_radioButton_switchCtrl_toggled(self, checked):
        if self.FullStatus.switchStatus != int(checked):
            cmd = DimmerParser.PackSetAttr("switch", "on", int(checked))
            self.SendCommandText(cmd)

    # 4、定时器
    @Slot()
    def on_pushButton_addTimer_clicked(self):
        if QDialog.Accepted == self.__TimerSetWindow.exec():
            timer = DimmerDevice.Timer()
            self.__TimerSetWindow.GetTimer(timer)
            cmd = DimmerParser.PackSetTimer(timer)
            print(cmd)
            self.SendCommandText(cmd)
    
    @Slot()
    def on_pushButton_delTimer_clicked(self):
        rowCount = self._ui.tableWidget_timers.currentRow()
        if rowCount >= 0:
            timer = copy.deepcopy(self.FullStatus.timers[rowCount])
            timer.week = 0
            cmd = DimmerParser.PackSetTimer(timer)
            self.SendCommandText(cmd)

    @Slot(QTableWidgetItem)
    def on_tableWidget_timers_itemDoubleClicked(self, item):
        rowCount = item.row()
        timer = copy.deepcopy(self.FullStatus.timers[rowCount])

        self.__TimerSetWindow.SetTimer(timer)
        if QDialog.Accepted == self.__TimerSetWindow.exec():
            self.__TimerSetWindow.GetTimer(timer)
            cmd = DimmerParser.PackSetTimer(timer)
            print(cmd)
            self.SendCommandText(cmd)

    @Slot()
    def on_pushButton_setDelay_clicked(self):
        delay = DimmerDevice.Delay()

        delay.enable = True
        delay.end = self._ui.dateTimeEdit_delayExecTime.dateTime().toSecsSinceEpoch()
        #灯开关
        delay.services.clear()
        switchOnoff = self._ui.comboBox_delaySwitchCtrl.currentIndex()
        delay.services.append(DimmerDevice.ServiceParams("switch", "on", switchOnoff))
        cmd = DimmerParser.PackSetDelay(delay)
        print(cmd)
        self.SendCommandText(cmd)

    @Slot()
    def on_pushButton_delDelay_clicked(self):
        if self.FullStatus.delay:
            delay = copy.deepcopy(self.FullStatus.delay)
            delay.enable = False
            # self._ui.dateTimeEdit_delayTime.setDateTime(QDateTime.currentDateTime())

            cmd = DimmerParser.PackSetDelay(delay)
            print(cmd)
            self.SendCommandText(cmd)
